//********************************************************
// PopupMenu.java
// Date: 5/1/2012
// Author: Andrew Landphier
//********************************************************
// Popup menu which displays the current contents of the players hand and color icon of the player. Icons and
// text based description. Upon selecting a choice it uses Tile.java to place the proper image on the 
// board at the specified board location. Upon selection a choice the popupmenu
// removes the tile from the players hand.
// ******************************************************
// EDITED by Jeff: Implemented the turn driver and upside down
// placement of tiles during initial setup. 
//*******************************************************

package ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.*;

import functionality.Player;
import functionality.Point;
import functionality.RobberKnights;
import ui.Tile;
import ui.data.BoardState;
import driver.Driver;


// NOTE: Needs static reference to the current acting player
// Not only do you need there hand you need to be able to the remove the tile from there hand once it is placed in the action listener

public class PopupMenu extends JPopupMenu implements ActionListener {
	String newline = "/n";
	private int menuCount;
	private static int PLAINCASTLE = 2, FORESTCASTLE = 5;
	private JMenuItem[] menuItem;
	private JPopupMenu popup;
	private String[] menuItemText;
	private ArrayList<Tile> pTiles;
	
	
	JPanel sourcePanel;
	
	
	public PopupMenu(JPanel source)	{
		popup = new JPopupMenu();
		sourcePanel = source;
	}
	
	/**
	 * PopupMenu that dynamically populates the menu items based off of the current player.
	 * Class is called from PopupListener
	 * @param source - Source JPanel from which the initial mouse event occured at (ie panel to add the tile to)
	 * @throws InterruptedException 
	 * @Auther Andrew Landphier/Jeff
	 */
	public JPopupMenu initialize() throws InterruptedException {
		//Get current players tiles in there hand		
		
		Driver.b.getStats();
		if(Driver.getTotalTurns()<=(Driver.getSize()*2))
		{
			System.out.println("First");
			int turnsLeft=2-Driver.getTurns();
			
			if(turnsLeft>0)
			{
				System.out.println("First4");
				while(Driver.getCurrentPlayer()==null){Thread.sleep(500);}	
			
					pTiles=Driver.getCurrentPlayer().getAllTileInHand();	
				
				//Get the tile count
				menuCount = pTiles.size();

				//Create appropriate sized menu arrays
				menuItemText = new String[menuCount];				
				menuItem = new JMenuItem[menuCount];				
				popup = new JPopupMenu();	  

				JLabel title=new JLabel("Player " + Driver.getCountTurns()+": Turns left= " + turnsLeft);
				title.setIcon(Driver.getCurrentPlayer().getIcon());
				popup.add(title);
				popup.addSeparator();

				
				if(turnsLeft==1)
				{
					System.out.println("First 1");
					String a="a";
					//Get the landscape of the tiles in the players hand	  		

					menuItemText[0] = pTiles.get(0).getLandScape()+","+pTiles.get(0).getBuildingStructure();
					menuItem[0]=new JMenuItem();					
					menuItem[0].setText("Place Tile "+ a +": " + menuItemText[0]);	 
					menuItem[0].setIcon(pTiles.get(0).getIcon());
					//Add Action Listeners to the objects
					menuItem[0].addActionListener(this);
					popup.add(menuItem[0]);
				}
				else
				{
					for (int i =0; i < menuCount; i++)
					{
						String a="a";
						//Get the landscape of the tiles in the players hand	  		

						menuItemText[i] = pTiles.get(i).getLandScape()+","+pTiles.get(i).getBuildingStructure();
						menuItem[i]=new JMenuItem();
						//Set the Menu item text
						if(i==1)a="b";

						menuItem[i].setText("Place Tile "+ a +": " + menuItemText[i]);	  
						menuItem[i].setIcon(pTiles.get(i).getIcon());
						//Add Action Listeners to the objects
						menuItem[i].addActionListener(this);

						popup.add(menuItem[i]);
					}				
				}

				return popup; 
			}
			//end turn
			else
			{
				System.out.println("DONE");
				popup = new JPopupMenu();	
				JLabel title=new JLabel("Player " + Driver.getCountTurns()+" NO Turns left " + turnsLeft);
				title.setIcon(Driver.getCurrentPlayer().getIcon());
				popup.add(title);
				popup.addSeparator();

				JMenuItem menuItem1=new JMenuItem();

				menuItem1.setText("End Turn");
				menuItem1.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {

						Driver.setTurn();
						popup.setVisible(false);
						popup=null;

					}

				});
				popup.add(menuItem1);
				return popup; 
			}
		}
		
		//5th turn
		else if(Driver.getTotalTurns()<=(Driver.getSize()*2)+1)
		{
			
			
			popup = new JPopupMenu();	
			JLabel title=new JLabel("Player " + Driver.getCountTurns()+" NO Turns left 0");
			title.setIcon(Driver.getCurrentPlayer().getIcon());
			popup.add(title);
			popup.addSeparator();

			JMenuItem menuItem1=new JMenuItem();

			menuItem1.setText("End Turn");
			menuItem1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					Driver.incTotalTurn();
					Driver.setTurn();

					for(int i=0;i<(Driver.getTotalTurns()-2);++i)
					{
						Tile s=BoardState.getTile(i);
						JPanel p=BoardState.getPanel(i);
						p.removeAll();
						p.add(new JLabel(new ImageIcon(s.getBufferedImage())));
						p.revalidate();
					}
					
					popup.setVisible(false);
					popup=null;

				}

			});
			popup.add(menuItem1);
			return popup; 
			
		}		
		//NORMAL GAME PLAY
		else
		{
			
			
		
		int turnsLeft=3-Driver.getTurns();
		
		if(turnsLeft>0)
		{

			while(Driver.getCurrentPlayer()==null){Thread.sleep(500);}		
			pTiles=Driver.getCurrentPlayer().getAllTileInHand();	

			//Get the tile count
			menuCount = pTiles.size();

			//Create appropriate sized menu arrays
			menuItemText = new String[menuCount];
			menuItem = new JMenuItem[menuCount+2];

			popup = new JPopupMenu();	  

			//add title

			JLabel title=new JLabel("Player " + Driver.getCountTurns()+": Turns left= " + turnsLeft);
			title.setIcon(Driver.getCurrentPlayer().getIcon());
			popup.add(title);
			popup.addSeparator();


			for (int i =0; i < menuCount; i++)
			{
				
				//Get the landscape of the tiles in the players hand	  		
				menuItemText[i] = pTiles.get(i).getLandScape()+", "+pTiles.get(i).getBuildingStructure();
				menuItem[i]=new JMenuItem();
				menuItem[i].setIcon(pTiles.get(i).getIcon());
				String a="a";
				if(i==1)a="b";
				menuItem[i].setText("Place Tile "+ a +": " + menuItemText[i]);	   //Set text		
				menuItem[i].addActionListener(this);
				popup.add(menuItem[i]);
			}
			
			
			if(turnsLeft<=2)
			{
			//end turn button
			menuItem[menuCount]=new JMenuItem();
			menuItem[menuCount].setText("End Turn");
			menuItem[menuCount].addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent arg0) 
				{
					Driver.incTotalTurn();
					Driver.setTurn();			
					
					popup.setVisible(false);
					popup=null;

				}
			

			});
			}
			if(turnsLeft<=2)
			{
				popup.add(menuItem[menuCount]);
			}
			
			


			return popup; 
		}
		//end turn
		else
		{
			popup = new JPopupMenu();	
			JLabel title=new JLabel("Player " + Driver.getCountTurns()+" NO Turns left " + turnsLeft);
			title.setIcon(Driver.getCurrentPlayer().getIcon());
			popup.add(title);
			popup.addSeparator();

			JMenuItem menuItem1=new JMenuItem();

			menuItem1.setText("End Turn");
			menuItem1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {

					Driver.setTurn();
					popup.setVisible(false);
					popup=null;
					if(Driver.done())
					{
						Driver.allDone();
					}
				}
			});
			popup.add(menuItem1);
			return popup; 
		}
	}
	}

	/**
	 * Matches the selected menuitem with the tile object in the initial list. Then 
	 * adds the corresponding JLabel Tile to the board.
	 * @Author Andrew Landphier/Jeff
	 */
	public void actionPerformed(ActionEvent e) {
		//System.out.println( e );
		Driver.b.getStats();
		if(Driver.getTotalTurns()<=(Driver.getSize()*2))
		{
			Driver.incTotalTurn();			
			if(Driver.getTurns()<2)
			{
				Driver.incTurn();

				if(Driver.getTurns()<=2)
				{
					if(Driver.getCurrentPlayer().hasTileLeft()||Driver.getCurrentPlayer().getNumCardsInHand()>0)
					{

						//Get the menu item that was selected
						JMenuItem source = (JMenuItem)(e.getSource());

						//Match the menu item index with the tile object
						//If there are still tiles in DECk
						for (int i =0; i < menuCount; i++) 
						{
							if (source == menuItem[i])
							{
								Tile t = pTiles.get(i);								
								
								pTiles.remove(i);
								//remove tile from hand and draws new card
								Driver.getCurrentPlayer().removeTileInHandTile(t);
								pTiles=Driver.getCurrentPlayer().getAllTileInHand();
								JLabel card=null;
								if(Driver.getCurrentPlayer().getColor().equals(Color.RED))
								{
									card=new JLabel(new ImageIcon("ICONS/red.jpg"));
								}
								else if(Driver.getCurrentPlayer().getColor().equals(Color.BLUE))
								{
									card=new JLabel(new ImageIcon("ICONS/blue.jpg"));
								}
								else if(Driver.getCurrentPlayer().getColor().equals(Color.GREEN))
								{
									card=new JLabel(new ImageIcon("ICONS/green.jpg"));
								}
								else if(Driver.getCurrentPlayer().getColor().equals(Color.YELLOW))
								{
									card=new JLabel(new ImageIcon("ICONS/yellow.jpg"));
								}
								
								//Add the correct tile label to the source JPanel+sets image on board
								sourcePanel.add(card);
								
								sourcePanel.revalidate();
								BoardState.addPanel(sourcePanel);
								t.setPanel(sourcePanel);

								//Disable the board panel after it has placed a tile
								//This disables the ability to select the spot on the board in the listener
								sourcePanel.setEnabled(false);

								// Get the x,y board coordinate of the action panel
								Point p = Board.matchTile(sourcePanel);
								
								t.setPoint(p);
								BoardState.addTile(t);
								//Get the integer representation of the tile
								int temp = Board.getTileInt(t);

								//Set the tile value in the BoardState array
								Board.setTile(p, temp);

		
								if (Board.checkInitialBoardState(Board.numplayers)) { //check initial board state
									Driver.placetile_lock = 1;
									Board.oneTimeBoardExpand(); //expand the board
								}

								if (Driver.placetile_lock == 1) 
								{
									Board.setAdjacentBackground(p.getX(), p.getY());
								}

							
		
							}					
						}
					}
					
					
				}
				else Driver.setTurnInt(2);
			}			
			
			//***********
			
		}
		else if(Driver.getTurns()<3)
		{
			
			
			Driver.incTurn();


			//System.out.println(Driver.turns+" turns plus player "+Driver.countTurn);
			if(Driver.getTurns()<=3)
			{
				if(Driver.getCurrentPlayer().hasTileLeft()||Driver.getCurrentPlayer().getNumCardsInHand()>0)
				{

					//Get the menu item that was selected
					JMenuItem source = (JMenuItem)(e.getSource());

					//Match the menu item index with the tile object
					//If there are still tiles in DECk
					for (int i =0; i < menuCount; i++) 
					{
						if (source == menuItem[i]){
							Tile t = pTiles.get(i);
							
							
							pTiles.remove(i);
							//remove tile from hand and draws new card
							Driver.getCurrentPlayer().removeTileInHandTile(t);
							pTiles=Driver.getCurrentPlayer().getAllTileInHand();

							
							//Add the correct tile label to the source JPanel+sets image on board
							sourcePanel.add(t.getLabel());
							sourcePanel.revalidate();
							//BoardState.addPanel(sourcePanel);
							t.setPanel(sourcePanel);

							//Disable the board panel after it has placed a tile
							//This disables the ability to select the spot on the board in the listener
							sourcePanel.setEnabled(false);

							// Get the x,y board coordinate of the action panel
							Point p = Board.matchTile(sourcePanel);
							t.setPoint(p);
							BoardState.addTile(t);
							
							int temp = Board.getTileInt(t);
							Board.setTile(p, temp);

							//Check to see if the initial board is setup
							//If so expand the board and unlock single placement expands
							if (Board.checkInitialBoardState(Board.numplayers)) {
								Driver.placetile_lock = 1;
								Board.oneTimeBoardExpand();
							}

							if (Driver.placetile_lock == 1) {
								Board.setAdjacentBackground(p.getX(), p.getY());
							}

							if (temp == PLAINCASTLE || temp == FORESTCASTLE) 
							{
								if (Driver.getCurrentPlayer().getNumKnights() > 0) {
									KnightPopup kp = new KnightPopup(Driver.b.frame, sourcePanel, p.getX(), p.getY());
									kp.Open();
									if(Driver.done())
									{
										Driver.allDone();
									}
								}
								
								
							}
							if(Driver.done())
							{
								Driver.allDone();
							}
						}					
					}
				}
				//No more tiles 
				
				else 
				{
					if(Driver.done())
					{
						Driver.allDone();
					}
					Driver.setTurnInt(3);
				}
			}

		}
	}
}